﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Cyss.Core.Helper
{
    /// <summary>
    /// 
    /// </summary>
    public static class ImageHelper
    {
        //将Image转换为byte[]
        public static byte[] ToBytes(this Image image)
        {

            MemoryStream ms = new MemoryStream();
            var format = image.RawFormat;
            if (format.Guid == ImageFormat.MemoryBmp.Guid)
            {
                format = ImageFormat.Bmp;
            }
            image.Save(ms, format);
            return ms.ToArray();
        }

        //将byte[]转换为Image
        public static Image ToImage(byte[] bytes)
        {
            return Image.FromStream(bytes.ToStream());
        }

        /// <summary>
        /// 剪切图片
        /// </summary>
        /// <param name="image"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public static Image GetShearImage(Image image, int x, int y, int w, int h)
        {

            //Image originalImage = Image.FromStream(stream);
            //新建一个bmp图片  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(w, h);

            //新建一个画板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充  
            g.Clear(System.Drawing.Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分  
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, w, h),
                        new System.Drawing.Rectangle(x, y, w, h),
                        System.Drawing.GraphicsUnit.Pixel);

            return bitmap;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="myByte"></param>
        /// <returns></returns>
        public static byte[] Rotate90FlipNone(byte[] myByte)
        {
            Image image = Image.FromStream(myByte.ToStream());
            image.RotateFlip(RotateFlipType.Rotate90FlipNone);
            MemoryStream memory = new MemoryStream();
            image.Save(memory, ImageFormat.Png);
            return memory.ToArray();
        }

        /// <summary>
        /// 获取图片缩略图
        /// </summary>
        /// <param name="pPath">图片路径</param>
        /// <param name="pSavePath">保存路径</param>
        /// <param name="pWidth">缩略图宽度</param>
        /// <param name="pHeight">缩略图高度</param>
        /// <param name="pFormat">保存格式，通常可以是jpeg</param>
        public static byte[] SetImageSize(byte[] bytes, int pWidth, int pHeight)
        {
            Image smallerImg;
            Image originalImg = Image.FromStream(bytes.ToStream());
            Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            smallerImg = originalImg.GetThumbnailImage(pWidth, pHeight, callback, IntPtr.Zero);
            MemoryStream memory = new MemoryStream();
            smallerImg.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            return memory.ToArray();

        }

        public static bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static byte[] MakeThumbnail(byte[] originalImage, int width, int height, ThumbnailModel mode)
        {
            Image image = Image.FromStream(originalImage.ToStream());
            var newImage = MakeThumbnail(image, width, height, mode);
            MemoryStream memory = new MemoryStream();
            newImage.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            return memory.ToArray();
        }

        /// <summary>  
        /// 生成图片缩略文件  
        /// </summary>  
        /// <param name="originalImage">图片源文件</param>  
        /// <param name="width">缩略图宽度</param>  
        /// <param name="height">缩略图高度</param>  
        /// <param name="mode">生成缩略图的方式</param>  
        /// <returns>缩率处理后图片文件</returns> 
        public static System.Drawing.Image MakeThumbnail(System.Drawing.Image originalImage, int width, int height, ThumbnailModel mode)
        {
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case ThumbnailModel.HighWidth: //指定高宽缩放（可能变形）   
                    break;
                case ThumbnailModel.Width: //指定宽，高按比例   
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailModel.Hight: //指定高，宽按比例  
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case ThumbnailModel.Default: //指定高，宽按比例  
                    if (ow <= towidth && oh <= toheight)
                    {
                        x = -(towidth - ow) / 2;
                        y = -(toheight - oh) / 2;
                        ow = towidth;
                        oh = toheight;
                    }
                    else
                    {
                        if (ow > oh)//宽大于高
                        {
                            x = 0;
                            y = -(ow - oh) / 2;
                            oh = ow;
                        }
                        else//高大于宽
                        {
                            y = 0;
                            x = -(oh - ow) / 2;
                            ow = oh;
                        }
                    }
                    break;
                case ThumbnailModel.Auto:
                    if (originalImage.Width / originalImage.Height >= width / height)
                    {
                        if (originalImage.Width > width)
                        {
                            towidth = width;
                            toheight = (originalImage.Height * width) / originalImage.Width;
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    else
                    {
                        if (originalImage.Height > height)
                        {
                            toheight = height;
                            towidth = (originalImage.Width * height) / originalImage.Height;
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    break;
                case ThumbnailModel.Cut: //指定高宽裁减（不变形）   
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = 0;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = 0;
                    }
                    break;
                default:

                    break;
            }

            //新建一个bmp图片  
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板  
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充  
            g.Clear(System.Drawing.Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分  
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

            return bitmap;
        }

        /// <summary>
        /// 等比例缩放图片
        /// </summary>
        /// <param name="bitmap">图片</param>
        /// <param name="destHeight">高度</param>
        /// <param name="destWidth">宽度</param>
        /// <returns></returns>
        public static byte[] ZoomImage(byte[] myByte, int destHeight, int destWidth)
        {

            System.Drawing.Image sourImage = Image.FromStream(myByte.ToStream()); ;
            int width = 0, height = 0;
            //按比例缩放
            int sourWidth = sourImage.Width;
            int sourHeight = sourImage.Height;
            if (sourHeight > destHeight || sourWidth > destWidth)
            {
                if ((sourWidth * destHeight) > (sourHeight * destWidth))
                {
                    width = destWidth;
                    height = (destWidth * sourHeight) / sourWidth;
                }
                else
                {
                    height = destHeight;
                    width = (sourWidth * destHeight) / sourHeight;
                }
            }
            else
            {
                width = sourWidth;
                height = sourHeight;
            }
            Image destBitmap = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(destBitmap);
            g.Clear(Color.Transparent);
            //设置画布的描绘质量
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //设置压缩质量
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;
            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            sourImage.Dispose();

            MemoryStream memory = new MemoryStream();
            destBitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
            return memory.ToArray();

        }



        /// <summary>
        /// 缩率图处理模式
        /// </summary>
        public enum ThumbnailModel
        {
            /// <summary>
            /// 指定高宽缩放（可能变形）   
            /// </summary>
            HighWidth,

            /// <summary>
            /// 指定宽，高按比例   
            /// </summary>
            Width,

            /// <summary>
            /// 默认  全图不变形   
            /// </summary>
            Default,

            /// <summary>
            /// 指定高，宽按比例
            /// </summary>
            Hight,

            /// <summary>
            /// 指定高宽裁减（不变形）？？指定裁剪区域
            /// </summary>
            Cut,

            /// <summary>
            /// 自动 原始图片按比例缩放
            /// </summary>
            Auto
        }


    }
}
